import {
  WechatyBuilder
} from 'wechaty'
import path from 'path';
import { FileBox } from 'file-box'
import fs from 'fs';

// const os = require('os');
      
const { machineIdSync } = require('node-machine-id');
// import { createCanvas, loadImage } from 'canvas';
// const { createCanvas, loadImage } = require('canvas');

// import QRCodeReader from 'qrcode-reader'; // 确保这是正确的导入语句
const Tesseract = require('tesseract.js');


// 创建一个新的 QRCodeReader 实例
// const reader = new QRCodeReader();


import { app, protocol, BrowserWindow, ipcMain, globalShortcut,Menu  } from 'electron'
import { createProtocol } from 'vue-cli-plugin-electron-builder/lib'
import installExtension, { VUEJS_DEVTOOLS } from 'electron-devtools-installer'
const isDevelopment = process.env.NODE_ENV !== 'production'

// Scheme must be registered before the app is ready
protocol.registerSchemesAsPrivileged([
  { scheme: 'app', privileges: { secure: true, standard: true } }
])

let eventS = null;
var bot = null;
var loginKey = "ding-dong-bot-tset"


async function createWindow() {
  // Create the browser window.
  const win = new BrowserWindow({
    width: 800,
    height: 800,
    webPreferences: {

      // Use pluginOptions.nodeIntegration, leave this alone
      // See nklayman.github.io/vue-cli-plugin-electron-builder/guide/security.html#node-integration for more info
      // nodeIntegration: process.env.ELECTRON_NODE_INTEGRATION,
      // contextIsolation: !process.env.ELECTRON_NODE_INTEGRATION,
      // preload: path.join(app.getAppPath(), '../elec_udp.js') // 渲染进程预加载
      preload: path.join(process.cwd(), '/lib/elec_udp.js'),
      webSecurity: false,//允许跨域请求
    }
    // webPreferences:{
    //   preload: path.resolve(__dirname,'../preload.js') // 渲染进程预加载
    // }

  })
   // 去掉菜单
   Menu.setApplicationMenu(null);
  // win.loadFile('index.html');
  // win.webContents.openDevTools()
  if (process.env.WEBPACK_DEV_SERVER_URL) {
    // Load the url of the dev server if in development mode
    await win.loadURL(process.env.WEBPACK_DEV_SERVER_URL)
    if (!process.env.IS_TEST) win.webContents.openDevTools()
  } else {
    createProtocol('app')
    // Load the index.html when not in development
    win.loadURL('app://./index.html')
  }
  // win.webContents.openDevTools()

  globalShortcut.register("CommandOrControl+Shift+i", function () {
    // mainWin.webContents.openDevTools();
    win.webContents.toggleDevTools();


  });
  globalShortcut.register("CommandOrControl+Shift+f", function () {
    let isFull = win.isFullScreen();
    win.setFullScreen(!isFull);
  });


}
// 在这里添加代码以支持多个实例
app.requestSingleInstanceLock();

// Quit when all windows are closed.
app.on('window-all-closed', () => {
  // On macOS it is common for applications and their menu bar
  // to stay active until the user quits explicitly with Cmd + Q
  if (process.platform !== 'darwin') {
    app.quit()
  }
})

app.on('activate', () => {
  // On macOS it's common to re-create a window in the app when the
  // dock icon is clicked and there are no other windows open.
  if (BrowserWindow.getAllWindows().length === 0) createWindow()
})

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.on('ready', async () => {
  // if (isDevelopment && !process.env.IS_TEST) {
  //   // Install Vue Devtools
  //   try {
  //     await installExtension(VUEJS_DEVTOOLS)
  //   } catch (e) {
  //     console.error('Vue Devtools failed to install:', e.toString())
  //   }
  // }
  createWindow()
  console.log("主进程启动成功输出来自 Vue 的消息"); // 输出来自 Vue 的消息

  ipcMain.on("receiving-broadcast", (event, arg) => {
    console.log("主进程接收到渲染进程的广播消息", arg)
    eventS = event;
    initChat();
  });

  // 主进程监听渲染进程传递过来的回调函数
  ipcMain.handle('render-info',async (event, args) => {
    console.log(args.type)
    switch (args.type) {
      case 10001:
        // 登录成功
        if (bot) {
          await bot.logout()
          await bot.stop()
        }
        initChat();
        break;
      case 10000:
        // 登录成功
        if (bot) {
          await bot.logout()
          await bot.stop()
        }
        initChat();
        break;
      case 10002: //发送消息
        console.log("10002", args.userData)
        // 收到消息
        sendMessage(args.userData, args.message)
        break;
      case 10003: //发送消息
        console.log("10003", args.userData)
        // 收到消息
        sendMessageImage(args.userData, args.message)
        break;

      case 10004: //获取机器码
        // console.log("10003", args.userData)
        if (eventS) {
          const msage = {
            type: 10004,
            content: getUUID()
          }
          console.log("发送消息给渲染进程  msage", msage)
          eventS.sender.send("broadcast-reply", msage);
        }

        break;
      default:
        break;
    }
  })

})

// Exit cleanly on request from parent process in development mode.
if (isDevelopment) {
  if (process.platform === 'win32') {
    process.on('message', (data) => {
      if (data === 'graceful-exit') {
        app.quit()
      }
    })
  } else {
    process.on('SIGTERM', () => {
      app.quit()
    })
  }
}
// import qrTerm from 'qrcode-terminal'
// import fs from 'fs';
// import { createCanvas, loadImage } from 'canvas';
// import jsQR from 'jsqr';



// import { FileBox } from 'file-box'


function onScan(qrcode, status) {
  const msage = {
    type: 0,
    content: "扫码登录",
    qrcode: qrcode,
    uuid: getUUID()
  }
  if (eventS) {
    eventS.sender.send("broadcast-reply", msage);
  }
}

async function onLogin(user) {
  console.log("onLogin", user);

  const name = await user.name()
 
  const msage = {
    type: 1,
    content: "登录成功",
    name: name,
    id: name,
    uuid: getUUID()
  }
  console.log("onLogin--------", msage, eventS)
  if (eventS) {
    eventS.sender.send("broadcast-reply", msage);
  }
  console.log(`${user.name()} login`)
}

async function onMessage(msg) {
  console.log("onMessage", msg.text())
  //屏蔽群消息
  if(msg.to() == null) return
  //更新联系人
  await msg.from().sync()
  //获取联系人昵称
  let alias = await msg.from().alias();
  if (!alias) {
    alias = await msg.from().name();
  }
  if (!alias) {
    return
  }

  if (msg.type() === bot.Message.Type.Text) {
    const msage = {
      type: 2,
      content: "收到消息",
      name: msg.from().name(),
      message: msg.text(),
      alias: alias,
    }
    console.log("onMessage  msage", msage)
    if (eventS) {
      console.log("发送消息给渲染进程  msage", msage)
      eventS.sender.send("broadcast-reply", msage);
    }
  } else if (msg.type() === bot.Message.Type.Image) {
    const fileBox = await msg.toFileBox()
    console.log("onMessage  fileBox", fileBox)
    // const base64Image = ;
    const imageMessage = `data:${fileBox._mediaType};base64,${Buffer.from(fileBox.buffer).toString('base64')}`;
    const msage = {
      type: 4,
      content: "收到消息",
      name: msg.from().name(),
      message:imageMessage,
      alias: alias,
    }
    if (eventS) {
      // console.log("发送消息给渲染进程  msage", msage)
      eventS.sender.send("broadcast-reply", msage);
    }

    // console.log("onMessage  base64Image", base64Image)
    // sendMessageImage({ alias: alias, name: alias }, base64Image)

    // // 读取图片文件
    // fs.readFile('path/to/image.jpg', (err, data) => {
    //   if (err) {
    //     console.error(err);
    //     return;
    //   }

    //   // 将图片数据转换为 base64 编码
    //   const base64Image = Buffer.from(data).toString('base64');

    //   // 输出 base64 编码
    //   console.log(base64Image);
    // });


  }
  // else if (msg.type() === bot.Message.Type.Image) {
  //   const fileBox = await msg.toFileBox()
  //   const ws = fs.createWriteStream(`./${fileBox.name}`);
  //   ws.write(fileBox.buffer, callback => {
  //     console.log(callback, "1------是否写入完成----")
  //     const msage = {
  //       type: 4,
  //       content: "收到图片消息",
  //       name: msg.from().name(),
  //       msgId: msg.from().id,
  //       path: path.join(__dirname, `../${fileBox.name}`)
  //     }
  //     if (eventS) {
  //       console.log("发送消息给渲染进程  msage", msage)
  //       eventS.sender.send("broadcast-reply", msage);
  //     }

  //   })
  // }



}

function onLogout(user) {
  const msage = {
    type: -1,
    content: "退出登录",
    name: user.name()
  }
  if (eventS) {
    eventS.sender.send("broadcast-reply", msage);
  }
  console.log(`${user.name()} logout`)
}

function initChat() {

  bot = WechatyBuilder.build()//{ name: loginKey }
  // bot = WechatyBuilder.build()
  bot.on('scan', onScan)
  bot.on('login', onLogin)
  bot.on('logout', onLogout)
  bot.on('message', onMessage)
  bot.on('error', onError)
  bot.on('friendship', onFriendship)
  bot.start()
    .catch(console.error)
}

// // 识别二维码的函数
// async function recognizeQRCode(imagePath) {
//   try {
//     if (!fs.existsSync(imagePath)) {
//       console.log(code, "-----没有文件-----")
//       throw new Error(`File not found: ${imagePath}`);
//     }

//     const image = await loadImage(imagePath);
//     const canvas = createCanvas(image.width, image.height);
//     const context = canvas.getContext('2d');

//     // 将图像绘制到画布上
//     context.drawImage(image, 0, 0, image.width, image.height);

//     // 获取图像数据
//     const imageData = context.getImageData(0, 0, image.width, image.height);
//     const code = jsQR(imageData.data, image.width, image.height);

//     console.log('Recognized QR code:', code ? code.data : null);
//     return code ? code.data : null;
//   } catch (error) {
//     console.error('Error recognizing QR code:', error);
//     return null;
//   }
// }
async function readQRCode(filePath) {
  console.log('Decoded data:', filePath); // 输出二维码数据
  Tesseract.recognize(filePath, 'eng') // 语言包，'eng'代表英语
    .then(({ data }) => {
      console.log('Decoded data:', data.text); // 输出二维码数据
    })
    .catch((err) => {
      console.error('Error reading QR code:', err);
    });
}


async function sendMessage(userData, message) {
  console.log("sendMessage", "昵稱查找");
  let contact = await bot.Contact.find({ alias: userData.alias })
  if (contact == null) {
    console.log("sendMessage", "用戶名查找", userData.name);
    contact = await bot.Contact.find({ name: userData.name })
  }
  if (contact == null) {
    return
  }
  console.log("sendMessage", "结束查找联系人", contact);
  await contact.say(message)
}

async function sendMessageImage(userData, base64Data) {
  console.log("sendMessage", "sendMessageImage");
  let contact = await bot.Contact.find({ alias: userData.alias })
  if (contact == null) {
    console.log("sendMessage", "用戶名查找", userData.name);
    contact = await bot.Contact.find({ name: userData.name })
  }
  if (contact == null) {
    return
  }
  const imageList = base64Data.split(',')
  console.log("imageList", imageList.length);

  if (imageList.length > 1) {
    const buffer = Buffer.from(imageList[1], 'base64')
    console.log("sendMessage", "用戶名查找", userData.name);
    if (imageList[0].includes("image/png")) {
      const file = FileBox.fromBuffer(buffer, 'image.png')
      console.log("sendMessage", "发送png");
      await contact.say(file)
    } else {
      const file = FileBox.fromBuffer(buffer, 'image.jpg')
      console.log("sendMessage", "发送jpg");
      await contact.say(file)
    }

  } else if (imageList.length > 0) {
    console.log("sendMessage", "默认发送jpg");
    const buffer = Buffer.from(imageList[0], 'base64')
    const file = FileBox.fromBuffer(buffer, 'image.jpg')
    console.log("sendMessage", "发送png");
    await contact.say(file)
  }

}


function onError(error) {
  console.error('Bot error:', error)
}

function onFriendship(friendship) {
  console.log('Bot received friendship event:', friendship)
}
// async function readQRCode(imageBuffer) {
//   try {
//     const result = await decode(imageBuffer);
//     console.log('Decoded data:', result.data); // 输出二维码数据
//   } catch (error) {
//     console.error('Error decoding QR code:', error);
//   }
// }

function getUUID() {
  // const networkInterfaces = os.networkInterfaces();
  // let macAddress = '';

  // for (const interfaceKey in networkInterfaces) {
  //   const networkInterface = networkInterfaces[interfaceKey];
  //   const interfaceInfo = networkInterface.find((details) => details.family === 'IPv4' && !details.internal);

  //   if (interfaceInfo) {
  //     macAddress = interfaceInfo.mac;
  //     break;
  //   }
  // }
  // return macAddress
  return machineIdSync().slice(0, 10);
}
